<template>
    <!-- 移动端顶部导航栏 -->
    <div class="mobile-nav">
        <div class="mobile-nav-header">
            <div class="mobile-logo">
                <img :src="icon" alt="logo" v-if="icon" />
                <span v-else class="mobile-team-name">{{ teamName }}</span>
            </div>
            <el-button class="mobile-menu-btn" @click="menuVisible = !menuVisible" text>
                <el-icon>
                    <Menu v-if="!menuVisible" />
                    <Close v-else />
                </el-icon>
            </el-button>
        </div>

        <!-- 主菜单抽屉 -->
        <el-drawer v-model="menuVisible" direction="rtl" size="180px" :with-header="false">
            <div class="mobile-menu-content">
                <!-- 用户信息 -->
                <div v-if="user" class="mobile-user-section">
                    <el-avatar :src="user.headportrait" :size="40">
                        {{ user.name?.charAt(0) }}
                    </el-avatar>
                    <div class="mobile-user-info">
                        <div class="mobile-user-name">{{ user.name }}</div>
                    </div>
                </div>

                <!-- 团队选择区域 -->
                <div v-if="teamList && teamList.length > 0" class="mobile-team-section">
                    <div v-if="teamList.length > 1" class="mobile-current-team clickable" @click="showTeamSelector">
                        <el-icon class="mobile-team-icon">
                            <OfficeBuilding />
                        </el-icon>
                        <span class="mobile-team-name-text">{{ currentTeam?.name || teamName }}</span>
                        <el-icon class="mobile-team-switch-icon">
                            <ArrowRight />
                        </el-icon>
                    </div>
                    <div v-else class="mobile-current-team">
                        <el-icon class="mobile-team-icon">
                            <OfficeBuilding />
                        </el-icon>
                        <span class="mobile-team-name-text">{{ currentTeam?.name || teamName }}</span>
                    </div>
                </div>

                <!-- 导航菜单 -->
                <div class="mobile-nav-menu">
                    <router-link v-for="item in navItems" :key="item.name" v-show="item.visible" :to="item.to"
                        class="mobile-nav-item" @click="closeMenu">
                        <el-icon>
                            <component :is="item.icon" />
                        </el-icon>
                        <span>{{ item.label }}</span>
                    </router-link>

                    <!-- 科学中心 -->
                    <router-link v-if="update" :to="{ name: '科学中心' }" class="mobile-nav-item" @click="closeMenu">
                        <el-icon>
                            <TrendCharts />
                        </el-icon>
                        <span>大数据</span>
                    </router-link>

                    <!-- 管理项 -->
                    <div v-if="managementVisible" class="mobile-nav-item" @click="handleManagement">
                        <el-icon>
                            <Management />
                        </el-icon>
                        <span>管理</span>
                    </div>
                </div>

                <!-- 用户操作 -->
                <div class="mobile-user-actions">
                    <div v-for="action in userActions" :key="action.command" v-show="action.visible"
                        class="mobile-action-item" :class="{ danger: action.danger }"
                        @click="handleAction(action.command)">
                        <el-icon>
                            <component :is="action.icon" />
                        </el-icon>
                        <span>{{ action.label }}</span>
                    </div>
                </div>
            </div>
        </el-drawer>

        <!-- 团队选择弹窗 -->
        <el-dialog v-model="teamDialogVisible" :width="'85%'" :top="'15vh'" :show-close="false"
            class="mobile-dialog-compact" append-to-body>
            <template #header>
                <div class="mobile-dialog-header">
                    <div class="mobile-dialog-title">
                        <el-icon class="mobile-dialog-title-icon">
                            <OfficeBuilding />
                        </el-icon>
                        <span>切换团队</span>
                    </div>
                    <el-button class="mobile-dialog-close-btn" @click="teamDialogVisible = false" text size="small">
                        <el-icon>
                            <Close />
                        </el-icon>
                    </el-button>
                </div>
            </template>

            <div class="mobile-team-selection">
                <!-- 搜索框 - 团队多时显示 -->
                <div class="mobile-team-search" v-if="teamList.length > 6">
                    <el-input v-model="teamSearchQuery" placeholder="搜索团队..." clearable size="small"
                        class="search-input-compact">
                        <template #prefix>
                            <el-icon>
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>
                </div>

                <!-- 团队列表 -->
                <div class="mobile-team-list">
                    <div v-for="team in filteredTeamList" :key="team.ID" class="mobile-team-item" :class="{
                        'active': currentTeam?.ID === team.ID,
                        'clickable': currentTeam?.ID !== team.ID
                    }" @click="handleTeamSelect(team)">
                        <div class="mobile-team-item-main">
                            <div class="mobile-team-item-name">{{ team.name }}</div>
                            <div class="mobile-team-item-id">ID: {{ team.ID }}</div>
                        </div>
                        <div class="mobile-team-item-status">
                            <el-icon v-if="currentTeam?.ID === team.ID" class="mobile-current-icon">
                                <Check />
                            </el-icon>
                            <el-icon v-else class="mobile-switch-icon">
                                <ArrowRight />
                            </el-icon>
                        </div>
                    </div>
                </div>

                <!-- 无结果提示 -->
                <div v-if="filteredTeamList.length === 0" class="mobile-no-teams">
                    <el-icon class="mobile-no-teams-icon">
                        <Search />
                    </el-icon>
                    <div class="mobile-no-teams-text">未找到匹配团队</div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {
    ArrowRight, Check, Checked, Close, Flag, Grid, HomeFilled,
    List, Management, Menu, OfficeBuilding, Platform, Search, Setting,
    SwitchButton, TrendCharts, User
} from '@element-plus/icons-vue';
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import * as routers from "../../ojSass/data/router";

interface Props {
    icon?: string
    teamName?: string
    user?: any
    isAdmin: boolean
    navPermissions?: string[]
    userMenuPermissions?: string[]
    routerNames?: string[]
    update?: boolean
    teamList?: any[]
    currentTeam?: any
}

const props = withDefaults(defineProps<Props>(), {
    icon: '',
    teamName: '码客行',
    user: null,
    navPermissions: () => [],
    userMenuPermissions: () => [],
    routerNames: () => [],
    update: false,
    teamList: () => [],
    currentTeam: null
})

const emit = defineEmits<{
    userAction: [command: string]
    management: []
    teamChange: [teamId: number]
}>()

// 状态管理
const isMobile = ref(false)
const menuVisible = ref(false)
const teamDialogVisible = ref(false)
const teamSearchQuery = ref('')

// 监听当前团队变化
watch(() => props.currentTeam?.ID, () => {
    teamDialogVisible.value = false
})

const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768
}

// 筛选团队列表
const filteredTeamList = computed(() => {
    if (!teamSearchQuery.value) {
        return props.teamList
    }
    return props.teamList.filter(team =>
        team.name.toLowerCase().includes(teamSearchQuery.value.toLowerCase()) ||
        team.ID.toString().includes(teamSearchQuery.value)
    )
})

// 导航配置 - 与ojSass保持一致
const navItems = computed(() => [
    {
        name: '首页',
        label: '首页',
        icon: HomeFilled,
        to: { path: '/home' },
        visible: checkNavPermission('首页')
    },
    {
        name: '题库',
        label: '题库',
        icon: Grid,
        to: routers.question,
        visible: checkNavPermission('题库')
    },
    {
        name: '题单',
        label: '专题',
        icon: List,
        to: routers.questionbank,
        visible: checkNavPermission('题单')
    },
    {
        name: '任务',
        label: '任务',
        icon: Checked,
        to: routers.task,
        visible: checkNavPermission('任务')
    },
    {
        name: '比赛',
        label: '比赛',
        icon: Flag,
        to: routers.activity,
        visible: checkNavPermission('比赛')
    },
    {
        name: '评测',
        label: '评测',
        icon: TrendCharts,
        to: routers.assessment,
        visible: props.isAdmin ? checkNavPermission('评测') : !!props.routerNames.find(e => e === '评测')
    },
    {
        name: '云课堂',
        label: '云课堂',
        icon: Platform,
        to: routers.cloudClass,
        visible: !props.update && checkNavPermission('云课堂')
    }
])

// 管理项可见性
const managementVisible = computed(() => {
    return checkNavPermission('管理') && props.isAdmin
})

// 用户操作配置
const userActions = computed(() => [
    {
        command: 'u',
        label: '个人中心',
        icon: User,
        visible: checkUserMenuPermission('个人中心'),
        danger: false
    },
    {
        command: 'a',
        label: '管理我的题目',
        icon: Grid,
        visible: checkUserMenuPermission('管理我的题目'),
        danger: false
    },
    {
        command: 'd',
        label: '修改个人信息',
        icon: Setting,
        visible: true,
        danger: false
    },
    {
        command: 'b',
        label: '退出登录',
        icon: SwitchButton,
        visible: true,
        danger: true
    }
])

// 权限检查
function checkNavPermission(name: string): boolean {
    return !props.navPermissions.includes(name)
}

function checkUserMenuPermission(name: string): boolean {
    return !props.userMenuPermissions.includes(name)
}

// 事件处理
function closeMenu() {
    menuVisible.value = false
}

function handleAction(command: string) {
    menuVisible.value = false
    emit('userAction', command)
}

function handleManagement() {
    menuVisible.value = false
    emit('management')
}

function showTeamSelector() {
    if (props.teamList.length <= 1) return
    teamSearchQuery.value = ''
    teamDialogVisible.value = true
}

function handleTeamSelect(team: any) {
    teamDialogVisible.value = false
    emit('teamChange', team.ID)
}

// 生命周期
onMounted(() => {
    checkMobile()
    window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
    window.removeEventListener('resize', checkMobile)
})
</script>

<style scoped>
/* 团队选择弹窗 - acCoderSaas 特有 */
.mobile-dialog-compact :deep(.el-dialog) {
    border-radius: 12px !important;
    max-height: 60vh !important;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.mobile-dialog-compact :deep(.el-dialog__body) {
    padding: 0 !important;
    max-height: calc(60vh - 60px);
    overflow: hidden;
}

.mobile-dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
    color: white;
    border-radius: 12px 12px 0 0;
}

.mobile-dialog-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
}

.mobile-dialog-title-icon {
    font-size: 18px;
}

.mobile-dialog-close-btn {
    color: white !important;
    width: 28px !important;
    height: 28px !important;
    border-radius: 50% !important;
}

.mobile-dialog-close-btn:hover {
    background: rgba(255, 255, 255, 0.2) !important;
}

/* 团队选择内容区域 - acCoderSaas 特有 */
.mobile-team-selection {
    display: flex;
    flex-direction: column;
    background: #fff;
    max-height: calc(60vh - 60px);
}

.mobile-team-search {
    padding: 16px 16px 8px;
    border-bottom: 1px solid var(--el-border-color-lighter);
}

.search-input-compact :deep(.el-input__wrapper) {
    border-radius: 20px;
    border: 1px solid var(--el-border-color);
    min-height: 36px;
}

.search-input-compact :deep(.el-input__inner) {
    font-size: 14px;
}

/* 团队列表 - acCoderSaas 特有 */
.mobile-team-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px 12px 12px;
    max-height: calc(60vh - 140px);
    -webkit-overflow-scrolling: touch;
}

.mobile-team-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    margin-bottom: 6px;
    border-radius: 8px;
    border: 1px solid var(--el-border-color-lighter);
    background: #fff;
    transition: all 0.2s ease;
    min-height: 60px;
}

.mobile-team-item:last-child {
    margin-bottom: 0;
}

.mobile-team-item.active {
    border-color: var(--el-color-success);
    background: linear-gradient(135deg, var(--el-color-success-light-9) 0%, #fff 100%);
    cursor: default;
}

.mobile-team-item.clickable {
    cursor: pointer;
}

.mobile-team-item.clickable:hover {
    border-color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.mobile-team-item:active {
    transform: scale(0.98);
}

.mobile-team-item-main {
    flex: 1;
    min-width: 0;
}

.mobile-team-item-name {
    font-size: 15px;
    color: var(--el-text-color-primary);
    font-weight: 600;
    line-height: 1.3;
    margin-bottom: 2px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.mobile-team-item-id {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    line-height: 1.2;
}

.mobile-team-item-status {
    display: flex;
    align-items: center;
    margin-left: 12px;
}

.mobile-current-icon {
    font-size: 20px;
    color: var(--el-color-success);
}

.mobile-switch-icon {
    font-size: 18px;
    color: var(--el-color-primary);
    transition: transform 0.2s;
}

.mobile-team-item.clickable:hover .mobile-switch-icon {
    transform: translateX(3px);
}

/* 无结果状态 - acCoderSaas 特有 */
.mobile-no-teams {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 20px;
    color: var(--el-text-color-secondary);
    min-height: 120px;
}

.mobile-no-teams-icon {
    font-size: 36px;
    margin-bottom: 12px;
    opacity: 0.6;
}

.mobile-no-teams-text {
    font-size: 14px;
    font-weight: 500;
}

/* 触摸优化 - acCoderSaas 特有 */
@media (hover: none) and (pointer: coarse) {
    .mobile-team-item.clickable:hover {
        transform: none;
        box-shadow: none;
        background: #fff;
        border-color: var(--el-border-color-lighter);
    }

    .mobile-team-item:active {
        transform: scale(0.96);
        transition: transform 0.1s;
    }
}

/* 响应式控制 - 组件特有 */
@media (max-width: 768px) {
    .mobile-nav {
        display: block;
    }
}

@media (min-width: 769px) {
    .mobile-nav {
        display: none !important;
    }
}
</style>
